package com.djdg.foodies.admin.base.exception;

import com.djdg.foodies.common.base.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

import static com.djdg.foodies.common.base.Result.fail;


/**
 * @Description: 全局异常处理
 * @Auther Demon
 * @Date 2017/12/15 17:55 星期五
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //添加全局异常处理流程，根据需要设置需要处理的异常
    @ExceptionHandler(value = Exception.class)
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) {
        // 未登录
        if (e instanceof UnAuthorizedException) {
            logger.error("用户未登录", e);
            return fail(HttpStatus.UNAUTHORIZED.value(), "未登录");
        }
        // 参数校验异常
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            String errorMsg = methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage();
            logger.error("参数校验出错: {}", errorMsg);
            return fail(errorMsg);
        }
        // 参数格式错误异常
        if (e instanceof MethodArgumentTypeMismatchException) {
            logger.error("非法参数: {}", e.getMessage());
            return fail("非法参数" + e.getMessage());
        }
        // 业务异常
        if(e instanceof FoodiesException) {
            logger.error("业务异常:" + e.getMessage());
            return fail(e.getMessage());
        }
        if(e instanceof HttpMessageNotReadableException) {
            logger.error("请求错误:" + e.getMessage());
            return fail("请求参数错误");
        }
        // 其他异常
        logger.error("服务器异常", e);
        return fail("服务器繁忙");
    }

}
